package com.warmheart.core.util.rsa;

import java.security.InvalidParameterException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @ClassName: RsaKeyUtil
 * @Description: 密钥生成工具
 * @author ZhangJianyang
 * @date 2025-06-16 09:37:02
 *
 */
public class RsaKeyUtil {

    private static Logger log = LoggerFactory.getLogger(RsaKeyUtil.class);

    /** 加密解密算法名称 */
    private static final String ALGORITHM = "RSA";

    /** 默认密钥大小 */
    private static final int KEY_SIZE = 1024;

    /** 密钥对生成器 */
    private static KeyPairGenerator keyPairGenerator = null;

    /** 缓存的密钥对 */
    private static KeyPair keyPair = null;

    /** Base64 编码/编码器 JDK1.8 */
    private static Base64.Encoder encoder = Base64.getEncoder();
    /** 初始化密钥工厂 */
    static {
        try {
            keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            log.error("RSAUtil[ERROR]:e={}", e);
        }
    }

    /**
     * 私有构造器，避免该类被作为对象使用
     * <p>
     * Title:
     * </p>
     * <p>
     * Description:
     * </p>
     * 
     * @author ZhangJianyang
     */
    private RsaKeyUtil() {
    }

    /**
     * * 生成密钥对 *
     * 将密钥分别用Base64编码保存到#publicKey.properties#和#privateKey.properties#文件中 *
     * 保存的默认名称分别为publicKey和privateKey
     */
    public static synchronized Map<String, String> generateKeyPair() {
        try {
            keyPairGenerator.initialize(KEY_SIZE, new SecureRandom(UUID.randomUUID().toString().replaceAll("-", "")
                    .getBytes()));
            keyPair = keyPairGenerator.generateKeyPair();
        } catch (InvalidParameterException e) {
            log.error("KeyPairGenerator does not support a key length of " + KEY_SIZE + ".", e);
        } catch (NullPointerException e) {
            log.error("RSAUtil#key_pair_gen is null,can not generate KeyPairGenerator instance.", e);
        }
        RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
        String publicKeyString = encoder.encodeToString(rsaPublicKey.getEncoded());
        String privateKeyString = encoder.encodeToString(rsaPrivateKey.getEncoded());
        Map<String, String> keyPair = new HashMap<>();
        keyPair.put("public", publicKeyString);
        keyPair.put("private", privateKeyString);
        return keyPair;
    }
}
